package cn.seecoder.courselearning.serviceimpl.course;

import cn.seecoder.courselearning.mapperservice.course.CommentsMapper;
import cn.seecoder.courselearning.mapperservice.course.CourseMapper;
import cn.seecoder.courselearning.po.course.Comments;
import cn.seecoder.courselearning.po.course.Course;
import cn.seecoder.courselearning.service.course.CommentsService;
import cn.seecoder.courselearning.util.Constant;
import cn.seecoder.courselearning.vo.ResultVO;
import cn.seecoder.courselearning.vo.course.CommentsVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {

    @Resource
    CommentsMapper commentsMapper;


    private int CmpByCreate(CommentsVO a, CommentsVO b){
        if (a.getCreateTime().before(b.getCreateTime())) {
            return 1;
        } else if (a.getCreateTime().after(b.getCreateTime())) {
            return -1;
        } else {
            return 0;
        }
    }

    private int CmpByUpdate(CommentsVO a, CommentsVO b){
        if (a.getUpdateT().before(b.getUpdateT())) {
            return 1;
        } else if (a.getUpdateT().after(b.getUpdateT())) {
            return -1;
        } else {
            return 0;
        }
    }

    @Override
    public List<CommentsVO> getAllComments(Integer courseId, Integer selectRule) {
        //System.out.println(courseId);
        List<Comments> tmpList = commentsMapper.selectCommentsByCourseId(courseId);
        List<CommentsVO> ret = new ArrayList<>();
        for (Comments c : tmpList) {
            ret.add(new CommentsVO(c));
        }

        if (selectRule == 1) {
            ret.sort(this::CmpByCreate);
        } else if (selectRule == 2) {
            ret.sort(this::CmpByUpdate);
        }
        return ret;
    }


    @Override
    public CommentsVO getComments(Integer CommentsID) {
        Comments comments = commentsMapper.selectCommentsByPrimaryKey(CommentsID);
        return new CommentsVO(comments);
    }

    @Override
    public ResultVO<CommentsVO> deleteComments(Integer commentsId) {
        if (commentsMapper.selectCommentsByPrimaryKey(commentsId) == null) {
            return new ResultVO<>(Constant.REQUEST_FAIL, "帖子不存在！");
        } else {
            commentsMapper.deleteByPrimaryKey(commentsId);
            return new ResultVO<>(Constant.ORDER_STATUS_SUCCESS, "帖子删除成功！");
        }
    }

    @Override
    public ResultVO<CommentsVO> createComments(CommentsVO commentsVO) {
        commentsVO.setCreateTime(new Date());
        commentsVO.setUpdateT(new Date());
        Comments comments = new Comments(commentsVO);
        if (commentsMapper.insert(comments) > 0) {
            return new ResultVO<>(Constant.REQUEST_SUCCESS, "课件创建成功", new CommentsVO(comments));
        }
        return new ResultVO<>(Constant.REQUEST_FAIL, "帖子创建失败");
    }
}
